import { useUserStoreHook } from "@/store/modules/user";
import { message } from "@/utils/message";

// 客户端错误处理（4xx状态码）
const errorMap = {
  401: { message: "登录状态已过期" },
  403: { message: "权限不足" },
  404: { message: "资源不存在" },
  400: { message: "参数错误" },
  429: { message: "请求过多" }
};

// 网络相关错误
const networkErrorMap = {
  ECONNABORTED: "请求超时",
  OFFLINE: "网络连接断开"
};
export const handleHttpError = error => {
  const { response, code } = error;
  const status = response?.status;

  // 服务器错误处理（5xx状态码）
  if (status >= 500) {
    return {
      type: "SERVER_ERROR",
      message: "服务器发生错误，请重新登录",
      redirect: true
    };
  }

  return {
    type: status ? "CLIENT_ERROR" : "NETWORK_ERROR",
    msg: errorMap[status]?.message || networkErrorMap[code] || "未知错误",
    redirect: status === 401
  };
};

export const redirectToLogin = async () => {
  useUserStoreHook().logOut();
  setTimeout(() => {
    message("服务器异常或业务错误，已退出当前账户！", {
      type: "error",
      duration: 3000
    });
    // const redirectUrl = '/login';
    // window.location.replace(redirectUrl);
    // window.location.replace(`/login?redirect=${encodeURIComponent(window.location.pathname)}`);
  }, 1000);
};

// 新增业务错误处理
export const handleBusinessError = (code: number, msg: string) => {
  message(
    msg || errorMap[code]?.message || networkErrorMap[code] || "未知错误",
    { type: "error" }
  );
  if (code === 403 || code === 401) {
    // redirectToLogin();
    return Promise.reject({ code, msg });
  }
  // 服务器错误处理（5xx状态码）
  if (code >= 500) {
    // redirectToLogin();
    return Promise.reject({
      code,
      msg: "服务器发生错误，请重新登录",
      redirect: true
    });
  }
  return Promise.reject({ code, msg });
};
